﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Diagnostics;
using System.Runtime.Remoting.Contexts;

using Castle.ActiveRecord;
using NHibernate.Criterion;
using LIB;

/// <summary>
/// Summary description for AuthenticateUtility
/// </summary>
public class AuthenticateUtility
{
    public static string GetUsername()
    {
        return HttpContext.Current.User.Identity.Name;
    }

    public static bool IsAuthenticated()
    {
        HttpContext context = HttpContext.Current;
        return
            context.User.Identity.IsAuthenticated;
    }

    public static void LoginUser(string _username, bool _rememberAccount)
    {
        LogoutUser();
        FormsAuthentication.Initialize();
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, _username, DateTime.Now, DateTime.Now.AddMinutes(30), _rememberAccount, "", FormsAuthentication.FormsCookiePath);
        Trace.Write(FormsAuthentication.FormsCookiePath + FormsAuthentication.FormsCookieName);
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
        HttpContext.Current.Response.SetCookie(cookie);

    }

    public static void LogoutUser()
    {
        HttpContext.Current.Items.Remove("MEMBER_INFO");
        HttpContext.Current.Session.Abandon();
        FormsAuthentication.SignOut();
    }

    public static Users_Info GetUserInfo()
    {
        ICriterion[] criteria = new ICriterion[] 
        {
            Expression.Eq("username", GetUsername())
        };
        return Users_Info.FindFirst(criteria);
    }

}
